import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { List, InputItem, TextareaItem, WhiteSpace, Button, Picker, Toast } from 'antd-mobile';
import { Form, Radio } from "antd";
// import moment from "moment";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
export interface ServiceItemPackageFormValues {
    id?: string;
}

/**
 * 组件：家属预约视图控件状态
 */
export interface FamilyAppointmentViewState extends ReactViewState {
    /** 基础数据 */
    base_data?: any;
    /** 生日 */
    date: any;
    /* 性别 */
    sex?: any;
    /** 状态 */
    state?: any;
    /** 身份证 */
    ldcard?: number;
    /** 证件类型 */
    id_card_type?: any;
    personnel_category?: any;
    organization_id?: any;
    organization_list?: any;
    organization_list_value?: any;
    organization_list_show_value?: any;
    homeAddress_detail?: any;
    residenceAddress_detail?: any;
    older_info?: any;
    name?: string;
    address?: string;
    tel?: string;
    sexs?: string;
}
/**
 * 组件：家属预约视图控件
 */
export class FamilyAppointmentView extends ReactView<FamilyAppointmentViewControl, FamilyAppointmentViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            date: '',
            base_data: {},
            sex: {
                sex: "男"
            },
            ldcard: undefined,
            id_card_type: { "id_card_type": "身份证" },
            personnel_category: { "personnel_category": "长者" },
            organization_id: {},
            organization_list: [],
            organization_list_show_value: '',
            homeAddress_detail: '',
            residenceAddress_detail: '',
            older_info: null,
            name: undefined,
            address: undefined,
            tel: undefined,

        };
    }
    componentDidMount() {
        // 判断是否登录
        AppServiceUtility.personnel_service.get_user_session!()!
            .then((data: any) => {
                if (!data) {
                    this.props.history!.push(ROUTE_PATH.login);
                    return;
                }
            });
        // this.autoFocusInst.focus();
        if (!this.props.match!.params.key) {
            AppServiceUtility.person_org_manage_service.get_all_organization_list!({ personnel_category: '福利院' })!
                .then((datas: any) => {
                    console.log(datas);
                    let organization_list: any[] = [];
                    if (datas) {
                        organization_list = datas.result.map((key: any, value: any) => {
                            let list = {};
                            list = { label: key['name'], value: key['id'] };
                            return list;
                        });
                        this.setState({
                            organization_list
                        });
                    }
                });

        } else {
            AppServiceUtility.person_org_manage_service.get_all_organization_list!({ id: this.props.match!.params.key })!
                .then((datas: any) => {
                    let organization_list: any[] = [];
                    console.log("养老院>>>>>>>", datas);
                    if (datas) {
                        organization_list = datas.result.map((key: any, value: any) => {
                            let list = {};
                            list = { label: key['name'], value: key['id'] };
                            return list;
                        });
                        let data = [];
                        data.push(organization_list[0].value);
                        this.setState({
                            organization_list,
                            organization_list_show_value: data,
                            organization_id: { "organization_id": data[0] },
                        });
                    }
                });
            if (this.props.location!.state.select_family_data!) {
                this.setState({
                    name: this.props.location!.state.select_family_data![0].family_person[0].name,
                    ldcard: this.props.location!.state.select_family_data![0].family_person[0].id_card,
                    sex: { 'sex': this.props.location!.state.select_family_data![0].family_person[0].personnel_info.sex, },
                    address: this.props.location!.state.select_family_data![0].family_person[0].personnel_info.address,
                    tel: this.props.location!.state.select_family_data![0].family_person[0].personnel_info.telephone,
                });

            }
        }
    }

    computedage = (IDCard: any) => {
        let userCard = IDCard;
        let yearBirth = userCard.substring(6, 10);
        let monthBirth = userCard.substring(10, 12);
        let dayBirth = userCard.substring(12, 14);
        let myDate = new Date();
        let monthNow = myDate.getMonth() + 1;
        let dayNow = myDate.getDay();
        let age = myDate.getFullYear() - yearBirth;
        if (monthNow < monthBirth || (monthNow === monthBirth && dayNow < dayBirth)) {
            age--;
        }
        return age;
    }

    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: ServiceItemPackageFormValues) => {
            // let date_birth = { "date_birth": moment(this.state.date).format("YYYY-MM-DD HH:mm") };
            let basic_information: any = {
                id_card: '',
                id_card_type: '',
                name: '',
                organization_id: '',
                address: '',
                personnel_info: {
                    age: '',
                    date_birth: null,
                    family_name: '',
                    id_card: '',
                    name: '',
                    personnel_category: '长者',
                    remarks: '',
                    sex: '',
                    telephone: ''
                },
                personnel_type: '1',
                remarks: '',
                // reservation_registration: {
                //     remarks: '',
                //     state: '网上预约'
                // }
            };
            basic_information.id_card = this.state.ldcard;
            basic_information.id_card_type = '身份证';
            basic_information.name = values['name'];
            basic_information.address = values['address'];
            basic_information.personnel_info.age = this.state.ldcard ? this.computedage(this.state.ldcard) : '';
            basic_information.personnel_info.date_birth = '';
            basic_information.personnel_info.id_card = this.state.ldcard;
            basic_information.personnel_info.name = values['name'];
            basic_information.personnel_info.remarks = values['comment'];
            basic_information.personnel_info.sex = this.state.sex.sex;
            basic_information.personnel_info.telephone = values['telephone'];
            basic_information.remarks = values['comment'];
            basic_information.organization_id = this.state.organization_id.organization_id;
            console.log(basic_information);
            AppServiceUtility.reservation_service.app_update_reservation_registration!(basic_information)!
                .then((data: any) => {
                    console.log(data);
                    if (data === '已经现场预约过了') {
                        Toast.fail('已经现场预约过了!!!', 2);
                    } else {
                        if (data === 'Success') {
                            Toast.success('预约成功!!!', 2, () => { this.props.history!.push(ROUTE_PATH.appointmentApplication); });
                        } else {
                            Toast.fail('预约失败!!' + data);
                        }
                    }
                });
        });
    }
    sexChange = (e: any) => {
        console.log("ceshi>>>>", e.target.value);
        if (e.target.value !== "{}") {
            this.setState({
                sex: { "sex": e.target.value }
            });
        } else {
            this.setState({
                sex: { "sex": '男' }
            });
        }
    }
    Changeorganization = (e: any) => {
        console.log(e);
        this.setState({
            organization_id: { "organization_id": e[0] },
            organization_list_show_value: e,
        });
    }
    handlelecard(e: any) {
        this.setState({
            ldcard: e
        });
        if (e !== null && e !== "") {
            if (e.length === 18) {
                let birthday = "";
                birthday = e.substr(6, 8);
                birthday = birthday.replace(/(.{4})(.{2})/, "$1,$2,");
                this.setState({
                    date: new Date(birthday),
                    ldcard: e
                });
            }
        }
    }
    changeName(e: any) {
        this.setState({
            name: e,
        });
    }
    changeAddress(e: any) {
        this.setState({
            address: e
        });
    }
    changeTel(e: any) {
        this.setState({
            tel: e,
        });
    }
    render() {
        // 地址区域数据
        const { getFieldProps } = this.props.form;
        return (
            <div>
                <Form>
                    <List renderHeader={() => '预约'}>
                        <Picker
                            data={this.state.organization_list ? this.state.organization_list : []}
                            value={this.state.organization_list_show_value}
                            cols={1}
                            onChange={(e) => this.Changeorganization(e)}
                            disabled={true}
                        >
                            <List.Item arrow="horizontal">组织</List.Item>
                        </Picker>
                        <InputItem {...getFieldProps('name')} value={this.state.name} onChange={this.changeName = this.changeName.bind(this)} placeholder="请输入申请人姓名">申请人</InputItem>
                        <InputItem {...getFieldProps('id_card')} placeholder="请输入身份证号码" value={this.state.ldcard} onChange={this.handlelecard = this.handlelecard.bind(this)}>身份证号码</InputItem>
                        <List.Item
                            extra={<Radio.Group disabled={true} value={this.state.sex.sex} onChange={this.sexChange}>
                                <Radio value={'男'}>男</Radio>
                                <Radio value={'女'}>女</Radio>
                            </Radio.Group>}
                        >性别
                        </List.Item>
                        {/* <DatePicker
                            mode="date"
                            title="生日"
                            extra="请选择生日"
                            value={this.state.date}
                            onChange={date => this.setState({ date })}
                            maxDate={new Date()}
                            minDate={new Date(1970, 0, 1)}
                        >
                            <List.Item arrow="horizontal">生日</List.Item>
                        </DatePicker> */}
                        <InputItem {...getFieldProps('address')} onChange={this.changeAddress = this.changeAddress.bind(this)} value={this.state.address} placeholder="请输入户籍地址">户籍地址</InputItem>
                        <InputItem {...getFieldProps('telephone')} onChange={this.changeTel = this.changeTel.bind(this)} placeholder="请输入联系电话" value={this.state.tel}>联系电话</InputItem>
                        <List renderHeader={() => '预约说明'}>
                            <TextareaItem
                                {...getFieldProps('comment', {
                                    initialValue: '',
                                })}
                                rows={5}
                                count={500}
                            />
                        </List>
                        <List.Item >
                            <Button type="primary" onClick={this.handleSubmit}>保存</Button>
                        </List.Item>
                        <WhiteSpace />
                    </List>
                </Form>
            </div >
        );
    }
}

/**
 * 组件：家属预约视图控件
 * 控制家属预约视图控件
 */
@addon('FamilyAppointmentView', '家属预约视图控件', '控制家属预约视图控件')
@reactControl(Form.create<any>()(FamilyAppointmentView), true)
export class FamilyAppointmentViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}